package tr.edu.yildiz.ce.dap.appagent.command.deployment.proxy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;

import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.AbstractAgentCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.AbstractCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandConstants;
import tr.edu.yildiz.ce.dap.appagent.exception.AgentDeploymentException;
import tr.edu.yildiz.ce.dap.appagent.exception.AgentRetryException;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.manager.ApplicationManager;
import tr.edu.yildiz.ce.dap.appagent.model.Actions;
import tr.edu.yildiz.ce.dap.appagent.model.Component;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.DeploymentProcess;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;
import tr.edu.yildiz.ce.dap.appagent.util.DeploymentConstants;
import tr.edu.yildiz.ce.dap.appagent.util.DeploymentUtils;

public class InstallCommand extends AbstractCommand {

	String applicationName ;
	String applicationVersion ;
	
	public InstallCommand(AbstractProcess process) {
		super(process);
		this.applicationName = applicationName;
		this.applicationVersion = applicationVersion;
	}

	@Override
	public DapMessage execute(DapMessage msg) throws BasicAgentException {
		DapMessage outputMessage = new  DapMessage();
		outputMessage.setCommand(CommandConstants.INSTALL);
		try{
			List<Component> cList = msg.getComponentList().getComponent();
			for (Component component : cList) {
				String bundleLocation = DeploymentUtils.downloadBundle(component);
				DeploymentUtils.installBundle(component, bundleLocation,getProcess().getProcessManager().getContext());
			}
		}catch (Exception e) {
			outputMessage.setResponse(CommandConstants.RESPONSE.DEPLOYMENT_FAILED);
		}
		ApplicationManager.addInstalledApplication(msg);
		outputMessage.setResponse(CommandConstants.RESPONSE.OK);
		return outputMessage;
	}
	


	@Override
	public DapMessage rollback(DapMessage msg) throws BasicAgentException {
		// TODO Auto-generated method stub
		return null;
	}

	
}
